package com.michael.ims.app.controller;

import com.michael.common.ex.BusinessException;
import com.michael.ims.app.*;
import com.michael.ims.app.cache.RightsService;
import com.michael.ims.app.cache.SystemService;
import com.michael.ims.app.config.SystemConfi;
import com.michael.ims.app.controller.io.rights.QuerySystemRightsReq;
import com.michael.ims.app.controller.io.rights.ValidateRightReq;
import com.michael.io.BaseUserInfoReq;
import com.michael.io.RespData;
import com.querydsl.core.Tuple;
import com.querydsl.sql.SQLQueryFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.Optional;

@Api(tags = "权限管理")
@RestController
@RequestMapping("/rights")
public class RightsController {
    private String regexp = SystemConfi.CONTEXT_PATH + "/(?<segment>.*)";

    private String replacement = "/${segment}";

    @Autowired
    private RightsService rightsService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private SQLQueryFactory sqlQueryFactory;

    @ApiOperation("获取用户指定系统的权限列表")
    @PostMapping("/system/query")
    @Transactional
    public RespData<List<String>> querySystemRights(@RequestBody @Valid QuerySystemRightsReq req) {
        QTblRight tblRight = QTblRight.tblRight;
        QTblUserToRole tblUserToRole = QTblUserToRole.tblUserToRole;
        QTblRoleToRight tblRoleToRight = QTblRoleToRight.tblRoleToRight;

        List<String> rights = sqlQueryFactory.select(tblRight.name)
                .from(tblRight).join(tblUserToRole).join(tblRoleToRight)
                .where(tblUserToRole.userId.eq(req.getUser().getId())
                        .and(tblUserToRole.roleId.eq(tblRoleToRight.roleId))
                        .and(tblRoleToRight.rightId.eq(tblRight.id))
                        .and(tblRight.isMenu.eq(req.getIsMenu()))
                        .and(tblRight.systemId.eq(req.getSystemId()))
                )
                .fetch();
        return new RespData<>(rights);
    }

//    @ApiOperation("获取用户的权限列表")
//    @PostMapping("/query")
//    public RespData<?> queryRights(@RequestBody @Valid BaseUserInfoReq req) {
//        return new RespData<>();
//    }

    @ApiOperation("校验用户是否具有权限访问")
    @PostMapping("/validate")
    @Transactional
    public RespData<Boolean> validate(@RequestBody @Valid ValidateRightReq req) {
        QTblSystem tblSystem = QTblSystem.tblSystem;
        //找出所属系统
        String systemPath = req.getFullPath().replaceAll(regexp, replacement);
        Tuple system = systemService.list().stream()
                .filter(tuple -> systemPath.startsWith("/" + tuple.get(tblSystem.context)))
                .findFirst()
                .orElseThrow(() -> new BusinessException("100003"));

        //查询该权限是否存在，如果不存在，则默认可以访问
        QTblRight tblRight = QTblRight.tblRight;
        Long rightId = sqlQueryFactory.select(tblRight.id)
                .from(tblRight)
                .where(tblRight.systemId.eq(system.get(tblSystem.id))
                        .and(tblRight.name.eq(systemPath))
                        .and(tblRight.isMenu.isFalse()))
                .fetchOne();
        if (rightId != null) {
            List<Long> rightList = rightsService.queryRights(req.getUid(), system.get(tblSystem.id));
            boolean acess = rightList.stream()
                    .anyMatch(right -> right.equals(rightId));
            return new RespData<>(acess);
        } else {
            return new RespData<>(true);
        }
    }

}
